簡單來說,就是呼叫函式內的函式,將記憶體封存在內層。
像這樣,我們把 count 封裝在 counter() 當中,不但可以讓裡面的 count 不會暴露在 global 環境造成變數衝突,也可以確保內部 count 被修改。
function counter(){
var count = 0;
function innerCounter(){
return ++count;
}
return innerCounter;
}
var countFunc = counter();
console.log( countFunc() ); // 1
console.log( countFunc() ); // 2
console.log( countFunc() ); // 3
function counter(){
var count = 0;
return function(){
return ++count;
}
}
var countFunc = counter();
var countFunc2 = counter();
console.log( countFunc() ); // 1
console.log( countFunc() ); // 2
console.log( countFunc() ); // 3
console.log( countFunc2() ); // 1
console.log( countFunc2() ); // 2
function callMethod(newMoney) {
var money = newMoney || 1000;
return function (price) {
money = money - price;
return money;
}
}
let updateMyMoney = callMethod(10000000000);
let updateYourMoney = callMethod(1000);
console.log(updateMyMoney(100));
console.log(updateYourMoney(100));
/*自調用函數,共用生存域*/
function Counter() {
let innerCounter = 0;
function change(val) {
innerCounter += val;
}
return {
addone: function() {
change(1);
},
deone: function() {
change(-1);
},
value: function() {
return innerCounter;
}
}
}
let newCounter = Counter()
console.log(newCounter.value()); /* logs 0 */
newCounter.addone();
newCounter.addone();
console.log(newCounter.value()); /* logs 2 */
newCounter.deone();
console.log(newCounter.value()); /* logs 1 */